package com.work.shart.common.mybatis.entity;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.google.common.collect.Lists;
import com.work.shart.common.util.FieldUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * 分页参数
 * @author cong
 * @param <T>
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageParams<T> {
    private T model;
    private long current = 1;
    private long size = 10;
    private String sort = BaseEntity.id_;
    private String order = "asc";

    /**
     * 功能: 构建分类参数对象
     * 功能描述: 排序字段以,隔开。注意 sort和order必须对应
     *
     * @param eClass
     * @param <E>
     * @return
     */
    public <E> IPage<E> buildPage(Class<?> eClass) {
        PageParams<T> pageParams = this;
        Page<E> page = new Page<>(pageParams.getCurrent(), pageParams.getSize());
        String[] property = pageParams.getSort().split(",");
        String[] order = pageParams.getOrder().split(",");
        List<OrderItem> orderItemList = Lists.newArrayList();
        for (int i = property.length - 1; i >= 0; i--) {
            String column = FieldUtil.getDbField(property[i], eClass);
            OrderItem orderItem = StrUtil.equalsAny(order[i], "asc", "ascing") ? OrderItem.asc(column) : OrderItem.desc(column);
            orderItemList.add(orderItem);
        }
        page.setOrders(orderItemList);
        return page;
    }
}
